import axios, {AxiosError, AxiosPromise, AxiosRequestConfig} from 'axios'
import {apiUrl, assetUrl, baseUrl} from "../config";
import networkHandle, {Code} from "./networkHandle";
import toast from "../component/common/ToastProxy";

export interface BaseResInterface {
    code: number,
    msg: string
}

export interface BaseResInterfaceWithData<T> {
    code: number,
    msg: string,
    data: T
}

interface ParamsErrorRes {
    location: string,
    param: string,
    msg: string
}

export interface ParamsErrorResInterface {
    errors: ParamsErrorRes[]
}

export async function sendPostRequest<T extends BaseResInterface>(url: string, params?: object, config?: AxiosRequestConfig): Promise<T> {

    return axios.post<T>(`${apiUrl}${url}`, params, config).then(function (res): T {
        // if (!networkHandle(res.status)) return null;
        // if (res.data.code !== Code.SUCCESS) toast("请求失败,服务器响应数据出错！");
        return res.data;
    }).catch(function (e: AxiosError): any {
        if (e.response) {
            networkHandle(e.response.status);
        } else {
            console.error(e);
            toast("未知错误！");
        }
    });


}

export async function uploadFile(uri: string, fileName: string) {
    function upload<T extends BaseResInterface>(params?: FormData): Promise<T> {
        return axios.post<T>(`${baseUrl}fileUpload`, params, {
            headers: {
                'Content-Type': 'multipart/form-data',
            }
        }).then(function (res): T {
            if (!networkHandle(res.status)) return null;
            return res.data;
        }).catch(function (e: AxiosError): any {
            if (e.response) {
                networkHandle(e.response.status);
            } else {
                console.error(e);
                toast("未知错误！");
            }
        });
    }

    const formData = new FormData();
    formData.append("file", {uri, type: 'multipart/form-data', name: fileName});
    const res = await upload<any>(formData);
    if (res["status"] === 200) {
        return res["file"];
    } else {
        throw new Error("上传图片失败");
    }
}


export function sendGetRequest<T extends BaseResInterface>(url: string, params?: object, config?: AxiosRequestConfig): Promise<T> {
    return axios.get<T>(`${apiUrl}${url}`, {...config, params}).then(function (res): T {
        // if (!networkHandle(res.status)) return null;
        return res.data;
    }).catch(function (e: AxiosError): any {
        if (e.response) {
            networkHandle(e.response.status);
        } else {
            toast("未知错误！");
        }
    });

}